﻿using DevExpress.Data;
using DevExpress.Data.XtraReports.Native;
using DevExpress.Mvvm;
using DevExpress.Pdf;
using DevExpress.Xpf.Charts;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Core.Native;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Grid.LookUp;
using DevExpress.XtraPrinting.Native;
using DevExpress.XtraRichEdit.Model;
using HandyControl.Controls;
using HandyControl.Tools;
using ImTools;
using Newtonsoft.Json;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Client.Models.Config;
using PlaceOrder_Client.ViewModels;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Shared.Models.Trade;
using Prism.DryIoc;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Application = System.Windows.Application;
using Brushes = System.Windows.Media.Brushes;
using Control = System.Windows.Controls.Control;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using RadioButton = System.Windows.Controls.RadioButton;
using TextBox = System.Windows.Controls.TextBox;
using Window = System.Windows.Window;

namespace PlaceOrder_Client.Views
{
    /// <summary>
    /// OrderView.xaml 的交互逻辑 订单窗体
    /// </summary>
    public partial class OrderView : HandyControl.Controls.Window
    {
        private SolidColorBrush originalBuyBtnBrush;
        private SolidColorBrush originalSellBtnBrush;
        public OrderViewModel _vm;

        private bool IsInError = false; // 是否在异常状态下
        public OrderView()
        {
            InitializeComponent();
            //SetAllControlsToGreen();
            dailyOrderStatus.Closed += DailyOrderStatus_Closed;
            Closed += OrderView_Closed;
     
            WindowEvent();

            originalBuyBtnBrush = (SolidColorBrush)buyBtn.Background;
            originalSellBtnBrush = (SolidColorBrush)sellBtn.Background;
            Messenger.Default.Register<int>(this, MessageToken.FengKong, HandleFengKongMessage);
            Messenger.Default.Register<string>(this, "saveOrderViewConfig", OnSaveOrderViewConfigMessageReceived);//保存下单配置
        }

        private void OrderView_Closed(object sender, EventArgs e)
        {
            // 取消注册 Messenger 消息
            Messenger.Default.Unregister<int>(this, MessageToken.FengKong, HandleFengKongMessage);
            Messenger.Default.Unregister<string>(this, "saveOrderViewConfig", OnSaveOrderViewConfigMessageReceived);

            // 关闭所有相关连接和清理资源
            //CloseAllConnections();
        }

        private void OnSaveOrderViewConfigMessageReceived(string obj)
        {
            this.SaveFavourite();
        }

        private void HandleFengKongMessage(int status)
        {
            switch (status)
            {
                case 0:
                case 1:
                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        buyBtn.Background = originalBuyBtnBrush;
                        sellBtn.Background = originalSellBtnBrush;
                    });
                    IsInError = false;
                    break;
                default:
                    PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                    {
                        buyBtn.Background = new SolidColorBrush(Colors.Gray);
                        sellBtn.Background = new SolidColorBrush(Colors.Gray);
                    });
                    IsInError = true;
                    break;
            }

            if (IsInError)
            {
                PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                    this.receiver.IsEnabled = false;
                    this.orderAmount.IsEnabled = false;
                    this.orderPrice.IsEnabled = false;

                    this.dateEdit.IsEnabled = false;
                    this.sellBtn.IsEnabled = false;
                    this.buyBtn.IsEnabled = false;
                });


                //Growl.WarningGlobal("当前状态异常中，禁止一切操作");
            }
            else
            {
                PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                {
                    this.receiver.IsEnabled = true;
                    this.orderAmount.IsEnabled = true;
                    this.orderPrice.IsEnabled = true;
                    this.dateEdit.IsEnabled = true;
                    this.sellBtn.IsEnabled = true;
                    this.buyBtn.IsEnabled = true;
                });

            }
        }

        private void WindowEvent()
        {
            TopBorder1.MouseMove += (s, e) =>
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                    this.DragMove();
            };

            btnMin.Click += (s, e) => { this.WindowState = WindowState.Minimized; };
            btnMax.Click += (s, e) =>
            {
                if (this.WindowState == WindowState.Maximized)
                    this.WindowState = WindowState.Normal;
                else
                    this.WindowState = WindowState.Maximized;
            };
            btnClose.Click += async (s, e) =>
            {
                this.Close();
            };
        }

        private void DailyOrderStatus_Closed(object? sender, EventArgs e)
        {
            // 执行关闭操作，比如隐藏 UserControl
            popup.IsOpen = false;
            //dailyOrderStatus.Visibility = Visibility.Hidden;
        }
  
        private void SetControlsForeColorToRed(UIElement element,SolidColorBrush solidColorBrush)
        {
            if (element == null)
                return;

            //// Check if the element is a Control and set its Foreground to Red
            //if (element is Control control)
            //{
            //    control.Foreground = solidColorBrush;
            //}

            //// Recursively handle children if the element is a panel
            //if (element is System.Windows.Controls.Panel panel)
            //{
            //    foreach (UIElement child in panel.Children)
            //    {
            //        SetControlsForeColorToRed(child, solidColorBrush);
            //    }
            //}
            //else if (element is ContentControl contentControl)
            //{
            //    SetControlsForeColorToRed(contentControl.Content as UIElement, solidColorBrush);
            //}
            //else if (element is ItemsControl itemsControl)
            //{
            //    foreach (object item in itemsControl.Items)
            //    {
            //        SetControlsForeColorToRed(item as UIElement, solidColorBrush);
            //    }
            //}
        }

        // Call this method, for example, in the constructor or a button click event
        private void SetAllControlsToRed()
        {
            //SolidColorBrush solidColorBrushRed = Brushes.Red;
            //SetControlsForeColorToRed(this.bottomPanel, solidColorBrushRed);
        }
        private void SetAllControlsToGreen()
        {
            //SolidColorBrush solidColorBrushLightGreen = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#3CB371")); // 使用淡绿色
            //SetControlsForeColorToRed(this.bottomPanel, solidColorBrushLightGreen);
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = sender as RadioButton;
            if (radioButton != null)
            {
                if (radioButton.Name == "buy")
                {
                    // Set color to green when "买" is selected
                    SetAllControlsToGreen();
                }
                else if (radioButton.Name == "sell")
                {
                    // Set color to red when "卖" is selected
                    SetAllControlsToRed();
                }
            }
        }

        private void LookUpEdit_CustomDisplayText(object sender, DevExpress.Xpf.Editors.CustomDisplayTextEventArgs e)
        {
            //e.DisplayText = $"1111222";
            e.DisplayText = "<No value>";
            e.Handled = true;
            //获取选中的项
            //if (e.EditValue is string && !((Item)e.EditValue).Id.HasValue)
            //{
            //    e.DisplayText = "<No value>";
            //    e.Handled = true;
            //}
        }

        private void OpenDrawer(object sender, RoutedEventArgs e)
        {
            // 切换 popup 的可见性
            popup.IsOpen = !popup.IsOpen;
            // 在显示 dailyOrderStatus 之前确保它的可见性为 Visible
            dailyOrderStatus.Visibility = Visibility.Visible;

            // 显示 dailyOrderStatus
            dailyOrderStatus.Show();

     

        }

        private void Window_Activated(object sender, EventArgs e)
        {
            // 设置RGB颜色值
            byte red = 255;    // 红色分量值（0-255）
            byte green = 143;    // 绿色分量值（0-255）
            byte blue = 75;     // 蓝色分量值（0-255）

            // 创建RGB颜色
            System.Windows.Media.Color color = System.Windows.Media.Color.FromRgb(red, green, blue);
            this.TopBorder1.Background = new SolidColorBrush(color); // 选中时的颜色
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            this.TopBorder1.Background = new SolidColorBrush(Colors.Transparent); // 选中时的颜色
        }
        private bool IsInExcludedControl()
        {
            // 检查是否焦点在被排除的控件上
            // 你可以根据需要扩展此方法以检查更多控件
            var focusedElement = Keyboard.FocusedElement as UIElement;
            if(focusedElement is System.Windows.Controls.TextBox)
            {
                // 尝试将焦点元素转换为 TextBox
                var textBox = focusedElement as System.Windows.Controls.TextBox;

                if(textBox.DataContext is DateEdit || textBox.DataContext is ComboBoxEdit || textBox.DataContext is SpinEdit)
                {
                    return true;
                }
            }
            return focusedElement is DateEdit; // 替换为实际的控件类型
        }

        private bool IsInOrderAmountControl()
        {
            // 获取当前获得键盘焦点的元素
            var focusedElement = Keyboard.FocusedElement as UIElement;

            if (focusedElement != null)
            {
                // 检查焦点元素是否是 TextBox 类型
                if (focusedElement is TextBox textBox)
                {
                    // 获取 TextBox 的 DataContext
                    var dataContext = textBox.DataContext;

                    // 检查 DataContext 是否是 SpinEdit 类型
                    if (dataContext is DevExpress.Xpf.Editors.SpinEdit spinEdit)
                    {
                        // 检查 SpinEdit 的 Tag 属性
                        return spinEdit.Tag?.ToString() == "orderAmount";
                    }
                }
            }

            return false;
        }



        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //if(tsCodeEdit.IsKeyboardFocusWithin)
            //{
            //    return;
            //}
            //Growl.SuccessGlobal("触发按键keydown");
            string keyValue = e.Key.ToString();
            if (IsInExcludedControl())
            {
                switch (keyValue)
                {
                    case "Return":
                        //_vm.PlaceAnOrder();
                        break;
                    case "Escape":
                        _vm.CancelOrder();
                        break;
                    case "F1":
                        _vm.IsBuyChecked = true;
                        _vm.IsSellChecked = false;
                        _vm.PlaceAnOrder();
                        break;
                    case "F2":
                        _vm.IsSellChecked = true;
                        _vm.IsBuyChecked = false;
                        _vm.PlaceAnOrder();
                        break;
                    default:
                        if(IsInOrderAmountControl()) // 选中量时候不能改数字
                        {
                            //if (keyValue.StartsWith("NumPad"))
                            //{
                            //    // 从 "NumPad" 后面截取数字字符
                            //    string numberString = keyValue.Substring(6);

                            //    // 将字符串转换为对应的数字
                            //    if (int.TryParse(numberString, out int number))
                            //    {
                            //        // 根据数字执行相应的逻辑
                            //        if (number == 0)
                            //        {
                            //            decimal price = 10000M; // 假设每个数字对应 1000
                            //            this.orderAmount.Value = price;
                            //        }
                            //        else
                            //        {
                            //            decimal price = number * 1000; // 假设每个数字对应 1000
                            //            this.orderAmount.Value = price;
                            //        }

                            //    }
                            //}
                            //else
                            //{
                            //    // 处理其他按键的逻辑
                            //}
                        }
                        
                        break;
                }
                return;
            }
            if (this.IsInError)
            {
                Growl.Warning("当前状态异常中，禁止下单相关操作",_vm.MsgToken);
                return;
            }
          

            // 检查是否按下了 Ctrl 键
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                switch (e.Key)
                {
                    case Key.D1: // Ctrl + 1
                        this.orderAmount.Value += 10000M;      // 处理 Ctrl + 1 的逻辑
                        break;
                    case Key.D2: // Ctrl + 2
                        this.orderAmount.Value += 20000M;         // 处理 Ctrl + 2 的逻辑
                        break;
                    case Key.D3: // Ctrl + 2
                        this.orderAmount.Value += 30000M;         // 处理 Ctrl + 2 的逻辑
                        break;
                    case Key.D4: // Ctrl + 2
                        this.orderAmount.Value += 40000M;         // 处理 Ctrl + 2 的逻辑
                        break;
                    case Key.D5: // Ctrl + 2
                        this.orderAmount.Value += 50000M;         // 处理 Ctrl + 2 的逻辑
                        break;

                    case Key.G: // Ctrl + G
                        _vm.ChangePrice();
                        break;
                    // 继续处理其他 Ctrl + 数字 的情况
                    default:
                        // 处理其他 Ctrl + 数字 的逻辑
                        break;
                }
            }
            else // 没有按下 Ctrl 键的其他情况
            {
                switch (keyValue)
                {
                    case "Return":
                        //_vm.PlaceAnOrder();
                        break;
                    case "Escape":
                        _vm.CancelOrder();
                        break;
                    case "F1":
                        _vm.IsBuyChecked = true;
                        _vm.IsSellChecked = false;
                        _vm.PlaceAnOrder();
                        break;
                    case "F2":
                        _vm.IsSellChecked = true;
                        _vm.IsBuyChecked = false;
                        _vm.PlaceAnOrder();
                        break;
                    case "Up":
                        this.orderPrice.Value += 0.0005m;
                        break;
                    case "Down":
                        this.orderPrice.Value = this.orderPrice.Value <= 0m ? 0m : this.orderPrice.Value - 0.0005m;
                        break;
                    case "Left":
                        this.orderPrice.Value = this.orderPrice.Value <= 0m ? 0m : this.orderPrice.Value - 0.0025m;
                        break;
                    case "Right":
                        this.orderPrice.Value += 0.0025m;
                        break;
                    default:
                        if (keyValue.StartsWith("NumPad"))
                        {
                            // 从 "NumPad" 后面截取数字字符
                            string numberString = keyValue.Substring(6);

                            // 将字符串转换为对应的数字
                            if (int.TryParse(numberString, out int number))
                            {
                                // 根据数字执行相应的逻辑
                                if (number == 0)
                                {
                                    decimal price = 10000M; // 假设每个数字对应 1000
                                    this.orderAmount.Value = price;
                                }
                                else
                                {
                                    decimal price = number * 1000; // 假设每个数字对应 1000
                                    this.orderAmount.Value = price;
                                }

                            }
                        }
                        else
                        {
                            // 处理其他按键的逻辑
                        }
                        break;
                }
            }
        }



        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _vm = this.DataContext as OrderViewModel;
        }

        private void receiver_PopupClosed(object sender, DevExpress.Xpf.Editors.ClosePopupEventArgs e)
        {

            ////获取 LookUpEdit 的 ItemsSource
            //var itemsSource = receiver.ItemsSource as IEnumerable<ChatReceiver>;
            //var chatreceiver = e.EditValue as ChatReceiver;
            //if (itemsSource != null)
            //{
            //    // 计算 IsDisabled 为 false 的项的数量
            //    var availableCount = itemsSource.Count(item => !item.IsDisabled && item.Brokerid != -1);
            //    if (availableCount == 1) //说明已经有对应中介,只能选对应
            //    {
            //        var OnlyBroker = itemsSource.Where(o => !o.IsDisabled && o.Brokerid != -1).FirstOrDefault();
            //        if (OnlyBroker != null)
            //        {
            //            // 判断当前选中的中介是否是自己能下单的那个中介
            //            if (chatreceiver != null && chatreceiver.Brokerid != -1 && chatreceiver.Brokerid != OnlyBroker.Brokerid)
            //            {
            //                // 将选中项置空
            //                Growl.WarningGlobal($"有正在处理的中介，只能选{OnlyBroker.FormattedTarget}以及自动");
            //                receiver.SelectedItem = OnlyBroker;

            //                // 取消 ClosePopupEventArgs 的默认行为，确保 LookUpEdit 不会保留之前的选中项
            //            }
            //        }

            //    }
            //    else // 允许选择任意未被占用的中介
            //    {
            //        // 如果当前选项已经被占用，显示警告并取消选择
            //        if (chatreceiver != null && chatreceiver.IsDisabled)
            //        {
            //            // 将选中项置空
            //            receiver.SelectedItem = null;
            //            Growl.WarningGlobal("该中介已被占用，请选其他");

            //            // 取消 ClosePopupEventArgs 的默认行为，确保 LookUpEdit 不会保留之前的选中项
            //        }
            //    }
            //}

            //if (chatreceiver.IsDisabled)
            //{
            //    // 将选中项置空
            //    receiver.SelectedItem = null;
            //    Growl.WarningGlobal("该中介已被占用，请选其他");
            //    // 取消 ClosePopupEventArgs 的默认行为，确保 LookUpEdit 不会保留之前的选中项
            //}
        }

        private void ComboBoxEdit_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //var textBox = (tsCodeEdit.Template.FindName("PART_EditableTextBox", tsCodeEdit) as TextBox);
            //if (textBox != null)
            //{
            //    Application.Current.Dispatcher.BeginInvoke(new Action(() => {
            //        textBox.SelectAll();
            //        textBox.Focus();
            //        //e.Handled = true;
            //    }));
            //}
        
            if (sender is ComboBoxEdit comboBoxEdit)
            {
                comboBoxEdit.Focus();
                comboBoxEdit.SelectAll();
                e.Handled = true;
            }
        }

        private void ComboBoxEdit_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            //if (sender is ComboBoxEdit comboBoxEdit)
            //{
            //    comboBoxEdit.SelectAll();
            //}
        }

        private void buyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.IsInError)
            {
                Growl.Warning("当前状态异常中，禁止下单相关操作",_vm.MsgToken);
                return;
            }
            _vm.IsBuyChecked = true;
            _vm.IsSellChecked = false;
            _vm.PlaceAnOrder();

        }

        private void sellBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.IsInError)
            {
                Growl.Warning("当前状态异常中，禁止下单相关操作", _vm.MsgToken);
                return;
            }
            _vm.IsSellChecked = true;
            _vm.IsBuyChecked = false;
            _vm.PlaceAnOrder();
        }


        private void GridControl_SelectedItemChanged(object sender, SelectedItemChangedEventArgs e)
        {
            UpdateSelectedBid();
        }

        private void GridControl_ItemsSourceChanged(object sender, DevExpress.Xpf.Grid.ItemsSourceChangedEventArgs e)
        {
            UpdateSelectedBid();
        }

        private void GridControl_ItemsSourceChanged2(object sender, DevExpress.Xpf.Grid.ItemsSourceChangedEventArgs e)
        {
            UpdateSelectedOfr();
        }

        private void GridControl_SelectedItemChanged2(object sender, SelectedItemChangedEventArgs e)
        {
            UpdateSelectedOfr();
        }

        public void UpdateSelectedBid()
        {
            if(_vm==null)
            {
                return;
            }

            if (_vm.SelectedBid != null)
            {
                // Get GridControl's GridView
                var gridControl = bidGridControl;
                var gridView = gridControl?.View as DevExpress.Xpf.Grid.TableView;

                if (gridView != null)
                {
                    string brokerName = _vm.SelectedBid.BrokerName;
                    int index = _vm.Bids.ToList().FindIndex(o => o.BrokerName == brokerName);
                    // 获取行句柄
                    var element = gridView.GetRowElementByRowHandle(index);
                    gridView.FocusedRowHandle = index;
                    //gridView.SelectRow((int)element.GetHandle());
                }
            }
        }

        public void UpdateSelectedOfr()
        {
            if(_vm==null)
            {
                AppLog.WriteError("UpdateSelectedOfr——vm为空？");
                return;
            }
            if (_vm.SelectedOfr != null)
            {
                // Get GridControl's GridView
                var gridControl = ofrGridControl;
                var gridView = gridControl?.View as DevExpress.Xpf.Grid.TableView;

                if (gridView != null)
                {
                    string brokerName = _vm.SelectedOfr.BrokerName;
                    int index = _vm.Ofrs.ToList().FindIndex(o => o.BrokerName == brokerName);
                    // 获取行句柄
                    var element = gridView.GetRowElementByRowHandle(index);
                    gridView.FocusedRowHandle = index;
                    //gridView.SelectRow((int)element.GetHandle());
                }
            }
        }


        /// <summary>
        /// 保存或移除 收藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToggleButton_Click(object sender, RoutedEventArgs e)
        {
            // 处理点击事件的逻辑
            var toggleButton = sender as ToggleButton;
            if (toggleButton != null)
            {
                // 执行所需操作，例如更新收藏状态
                bool isFavourite = toggleButton.IsChecked ?? false;
                // 更新模型或执行其他操作
                // Example: UpdateFavouriteStatus(isFavourite);
                if(isFavourite)
                {
                    SaveFavourite();
                }else
                {
                    RemoveFavourite();
                }
            }
        }


        protected override void OnClosed(EventArgs e)
        {
            try
            {
                base.OnClosed(e);
                if (_vm == null)
                {
                    return;
                }
                else
                {
                    _vm?.websocket?.Dispose();
                    _vm?.DisposeAllTimers();
                    _vm = null;

                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("关闭OrderView时异常"+ex.Message);
            }
           
            //bool isFavourite = _vm.IsFavourite;
            //if(isFavourite)
            //{
            //    SaveFavourite();
            //}

        }

        private void SaveFavourite()
        {
            try
            {
                if (string.IsNullOrEmpty(_vm.BondNumber))
                {
                    Growl.Warning($"券码为空，无法收藏",_vm.MsgToken);
                    return;
                }
                string ConfigFilePath = MainViewModel.ConfigFilePath;
                // 读取现有配置
                WindowConfig existingConfig = null;
                if (File.Exists(ConfigFilePath))
                {
                    string existingJson = File.ReadAllText(ConfigFilePath);
                    existingConfig = JsonConvert.DeserializeObject<WindowConfig>(existingJson);
                }
                int day = int.TryParse(Regex.Match(_vm.CbDays, @"\d+").Value, out var temp) ? temp : default;
                var newWindowPosition = new WindowPosition
                {
                    Top = this.Top,
                    Left = this.Left,
                    Width = this.ActualWidth,
                    Height = this.ActualHeight,
                    TsCode = _vm.BondNumber,
                    CbDays = day,
                    IsFavourite = true // 设为收藏
                };
                // 如果没有现有配置，则初始化一个新的配置对象
                if (existingConfig == null)
                {
                    existingConfig = new WindowConfig
                    {
                        WindowPositions = new Dictionary<string, List<WindowPosition>>()
                    };
                }

                // 确保 "OrderView" 键存在
                if (!existingConfig.WindowPositions.ContainsKey("OrderView"))
                {
                    existingConfig.WindowPositions["OrderView"] = new List<WindowPosition>();
                }

                // 查找现有的 TsCode 条目
                var orderViewPositions = existingConfig.WindowPositions["OrderView"];
                var existingPosition = orderViewPositions.FirstOrDefault(p => p.TsCode == _vm.BondNumber);

                int flag = 0;
                if (existingPosition != null)
                {
                    // 如果 TsCode 存在，覆盖现有条目
                    orderViewPositions.Remove(existingPosition);
                    flag = 1;
                }
                // 新增条目
                orderViewPositions.Add(newWindowPosition);

                // 将更新后的配置序列化为 JSON 字符串
                string json = JsonConvert.SerializeObject(existingConfig, Formatting.Indented);

                // 保存到文件
                File.WriteAllText(ConfigFilePath, json);

                if(flag==0)
                {
                    // 记录日志和显示成功消息
                    Growl.Success($"收藏{_vm.BondNumber}券码成功",_vm.MsgToken);
                }else
                {
                    // 记录日志和显示成功消息
                    Growl.Success($"覆盖原配置，收藏{_vm.BondNumber}券码成功", _vm.MsgToken);
                }
         
            }
            catch(Exception ex)
            {
                AppLog.WriteError($"收藏{_vm.BondNumber}券码异常,{ex.Message}-{ex.StackTrace}");
            }
            
        }

        private void RemoveFavourite()
        {
            string ConfigFilePath = MainViewModel.ConfigFilePath;

            try
            {
                if(string.IsNullOrEmpty(_vm.BondNumber))
                {
                    Growl.Warning($"券码为空，无法移除", _vm.MsgToken);
                    return;
                }
                // 读取现有配置
                WindowConfig existingConfig = null;

                if (File.Exists(ConfigFilePath))
                {
                    string existingJson = File.ReadAllText(ConfigFilePath);
                    existingConfig = JsonConvert.DeserializeObject<WindowConfig>(existingJson);
                }

                if (existingConfig == null || !existingConfig.WindowPositions.ContainsKey("OrderView"))
                {
                    // 如果没有配置或没有 "OrderView" 键，直接返回
                    Growl.Warning($"未找到 {_vm.BondNumber} 的收藏记录", _vm.MsgToken);
                    return;
                }

                // 获取 "OrderView" 下的所有窗口位置
                var orderViewPositions = existingConfig.WindowPositions["OrderView"];
                var existingPosition = orderViewPositions.FirstOrDefault(p => p.TsCode == _vm.BondNumber);

                if (existingPosition != null)
                {
                    // 如果 TsCode 存在，移除条目
                    orderViewPositions.Remove(existingPosition);

                    // 如果 "OrderView" 下没有更多的项，移除该键
                    if (orderViewPositions.Count == 0)
                    {
                        existingConfig.WindowPositions.Remove("OrderView");
                    }

                    // 将更新后的配置序列化为 JSON 字符串
                    string json = JsonConvert.SerializeObject(existingConfig, Formatting.Indented);

                    // 保存到文件
                    File.WriteAllText(ConfigFilePath, json);

                    // 记录日志和显示成功消息
                    Growl.Success($"已移除 {_vm.BondNumber} 的收藏记录", _vm.MsgToken);
                }
                else
                {
                    // 如果没有找到指定的 TsCode
                    Growl.Warning($"未找到 {_vm.BondNumber} 的收藏记录", _vm.MsgToken);
                }
            }
            catch (Exception ex)
            {
                // 处理异常情况，记录错误日志
                AppLog.WriteError("移除收藏失败：" + ex.Message);
                Growl.Error("移除收藏失败：" + ex.Message,_vm.MsgToken);
            }
        }

        private void ChartControl_BoundDataChanged(object sender, RoutedEventArgs e)
        {

            //var diagram = chartControl.Diagram as XYDiagram2D;
            //if (diagram != null)
            //{
            //    AdjustAxisRange(diagram.AxisX);
            //}
        }
        //private void AdjustAxisRange(Axis2D axis)
        //{
        //    var visualRange = axis.VisualRange;
        //    var wholeRange = axis.WholeRange;

        //    // 判断是否需要缩放视图范围
        //    if (visualRange.MinValue.Equals(wholeRange.MinValue) && visualRange.MaxValue.Equals(wholeRange.MaxValue))
        //    {
        //        // 将视觉范围设定为与整体范围相同（不缩放）
        //        visualRange.SetMinMaxValues(wholeRange.MinValue, wholeRange.MaxValue);
        //    }
        //    else
        //    {
        //        // 如果用户缩放了图表，允许滚动条显示
        //        axis.VisualRange.SetMinMaxValues(visualRange.MinValue, visualRange.MaxValue);
        //    }
        //}

        private void XYDiagram2D_Zoom(object sender, XYDiagram2DZoomEventArgs e)
        {
            XYDiagram2D diagram = (XYDiagram2D)sender;

            if (e.AxisX.ActualWholeRange.ActualMaxValueInternal == e.NewXRange.Max &&
                e.AxisX.ActualWholeRange.ActualMinValueInternal == e.NewXRange.Min)
                diagram.DefaultPane.AxisXScrollBarOptions.Visible = false;
            else
                diagram.DefaultPane.AxisXScrollBarOptions.Visible = true;
        }

        private async void OrderPrice_GotFocus(object sender, RoutedEventArgs e)
        {
            var spinEdit = sender as DevExpress.Xpf.Editors.SpinEdit;
            if (spinEdit != null )
            {
                // 设置焦点并全选文本
                await PrismApplication.Current.Dispatcher.InvokeAsync(spinEdit.SelectAll, DispatcherPriority.Background);
            }
            e.Handled = true;
        }

        private async void tsCodeEdit_GotFocus(object sender, RoutedEventArgs e)
        {
            var comboBoxEdit = sender as DevExpress.Xpf.Editors.ComboBoxEdit;
            if (comboBoxEdit != null && !comboBoxEdit.IsPopupOpen)
            {
                // 确保焦点和全选操作在事件处理完成后执行
                await PrismApplication.Current.Dispatcher.BeginInvoke(new Action(() =>
                 {
                     comboBoxEdit.SelectAll();
                 }), DispatcherPriority.Background);
            }
        }

        private async void orderAmount_GotFocus(object sender, RoutedEventArgs e)
        {
            var orderAmount = sender as DevExpress.Xpf.Editors.SpinEdit;
            if (orderAmount != null)
            {
                // 设置焦点并全选文本
                await PrismApplication.Current.Dispatcher.InvokeAsync(orderAmount.SelectAll, DispatcherPriority.Background);
            }
            e.Handled = true;
        }

        private async void tsCodeEdit_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var comboBox = sender as DevExpress.Xpf.Editors.ComboBoxEdit;
            if (comboBox != null && !comboBox.IsKeyboardFocusWithin)
            {
                // 防止事件继续传递
                e.Handled = true;

                // 设置焦点并全选文本
                comboBox.Focus();
                comboBox.Dispatcher.BeginInvoke(new Action(comboBox.SelectAll), DispatcherPriority.Input);
            }
            //var comboBoxEdit = sender as DevExpress.Xpf.Editors.ComboBoxEdit;
            //if (comboBoxEdit != null && !comboBoxEdit.IsPopupOpen)
            //{
            //    // 确保焦点和全选操作在事件处理完成后执行
            //    await PrismApplication.Current.Dispatcher.BeginInvoke(new Action(() =>
            //    {
            //        comboBoxEdit.SelectAll();
            //    }), DispatcherPriority.Background);
            //    e.Handled = true;
            //}
        }

        /// <summary>
        /// 点击空白自动取消焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Keyboard.ClearFocus();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //// 清除当前输入控件的焦点
            //Keyboard.ClearFocus();

            //// 将焦点设置回窗口以确保可以接收到键盘事件
            //FocusManager.SetFocusedElement(this, this);


            //e.Handled = true;
        }

        private void TransitioningContentControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //Growl.SuccessGlobal("清除第五行控件焦点");
            // 清除当前输入控件的焦点
            //Keyboard.ClearFocus();
            //string clipboardStr = System.Windows.Clipboard.GetText();
            //AppLog.WriteInfo($"清空剪贴板前,数据为{clipboardStr}");

            //System.Windows.Clipboard.Clear(); // bug 要清空剪贴板！
            //AppLog.WriteInfo($"清空剪贴板后,数据为{clipboardStr}");
            string clipboardStr = System.Windows.Clipboard.GetText();
            AppLog.WriteInfo($"清空剪贴板前,数据为{clipboardStr}");

            System.Windows.Clipboard.Clear(); // bug 要清空剪贴板！
            clipboardStr = System.Windows.Clipboard.GetText();
            AppLog.WriteInfo($"清空剪贴板后,数据为{clipboardStr}");
            FocusManager.SetFocusedElement(this, this);
            //e.Handled = true;
        }
    }
}
